﻿using Nop.Core.Domain.Customers;
using Nop.Core.Domain.XJ;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.XJ;
using Nop.Web.Framework.Security;
using Nop.Web.Models.Home;
using Nop.Web.Models.XJ;
using System;
using System.Linq;
using System.Web.Mvc;

namespace Nop.Web.Controllers
{
	public class InspectionPlanController : Controller
	{
		#region Fields
		private readonly IDepartmentService _departmentService;
		private readonly ICustomerService _customerService;
		private readonly IFilesService _filesService;
		private readonly IPictureService _pictureService;
		private readonly IMessageService _messageService;
		private readonly ILogger _logger;
		private readonly IGenericAttributeService _genericAttributeService;
		private readonly IXJPlaceService _xjPlaceService;
		private readonly IXJEquipmentCategoryService _xJEquipmentCategoryService;
		private readonly IXJEquipmentService _xJEquipmentService;
		private readonly IXJEquipmentStockService _xJEquipmentStockService;
		private readonly IXJInspectionService _xJInspectionService;
		private readonly IXJInspectionPlanService _xJInspectionPlanService;
		private readonly IXJMaintenanceService _xJMaintenanceService;
		private readonly IXJMaintenanceCommentService _xJMaintenanceCommentService;
		#endregion

		#region Ctor
		public InspectionPlanController(
			IDepartmentService departmentService,
			ICustomerService customerService,
			IFilesService filesService,
			IPictureService pictureService,
			IMessageService messageService,
			ILogger logger,
			IGenericAttributeService genericAttributeService,
			IXJPlaceService xjPlaceService,
			IXJEquipmentCategoryService xJEquipmentCategoryService,
			IXJEquipmentService xJEquipmentService,
			IXJEquipmentStockService xJEquipmentStockService,
			IXJInspectionService xJInspectionService,
			IXJInspectionPlanService xJInspectionPlanService,
			IXJMaintenanceService xJMaintenanceService,
			IXJMaintenanceCommentService xJMaintenanceCommentService)
		{
			this._departmentService = departmentService;
			this._customerService = customerService;
			this._filesService = filesService;
			this._pictureService = pictureService;
			this._messageService = messageService;
			this._logger = logger;
			this._genericAttributeService = genericAttributeService;
			this._xjPlaceService = xjPlaceService;
			this._xJEquipmentCategoryService = xJEquipmentCategoryService;
			this._xJEquipmentService = xJEquipmentService;
			this._xJEquipmentStockService = xJEquipmentStockService;
			this._xJInspectionService = xJInspectionService;
			this._xJInspectionPlanService = xJInspectionPlanService;
			this._xJMaintenanceService = xJMaintenanceService;
			this._xJMaintenanceCommentService = xJMaintenanceCommentService;
		}
		#endregion

		/// <summary>
		/// 我的巡检计划
		/// </summary>
		/// <param name="customer"></param>
		/// <param name="typeId"></param>
		/// <param name="categoryId"></param>
		/// <param name="pageIndex"></param>
		/// <param name="pageSize"></param>
		/// <returns></returns>
		[HttpPost]
		[UserValidator]
		public JsonResult List(Customer customer, int typeId = 0, int categoryId = 0, string name = "", bool onlyBacklog = false, int pageIndex = 0, int pageSize = 10)
		{
			if (null == customer || customer.Deleted)
				return Json(new { result = false, msg = "用户无效" });

			var plans = _xJInspectionPlanService.GetMyInspectionPlans(
				customer: customer,
				typeId: typeId,
				categoryId: categoryId,
				categoryName: name,
				onlyBacklog: onlyBacklog,
				pageIndex: pageIndex,
				pageSize: pageSize);
			return Json(new
			{
				result = true,
				model = plans.Select(f =>
				{
					string title = f.Name;
					if (string.IsNullOrEmpty(title))
					{
						title = f.AimId == (int)AimTypeEnum.设备分类 ? string.Join(",", f.Categorys.Select(x => x.Name)) : string.Join(",", f.Places.Select(x => x.Name));
					}
					var item = new ListItemModel
					{
						Id = f.Id,
						Title = title,
						Value = Enum.GetName(typeof(InspectionTypeEnum), f.TypeId),
						Label = string.Format("{0}{1} {2}", f.TeamName, f.PersonName, f.LastUpdateOn.HasValue ? f.LastUpdateOn.Value.ToString("yyyy-MM-dd HH:mm") : ""),
					};
					return item;
				}),
				plans.PageIndex,
				plans.TotalPages
			});
		}

		[HttpPost]
		[UserValidator]
		public JsonResult View(Customer customer, int planId)
		{
			var model = new InspectionPlanModel();
			var plan = _xJInspectionPlanService.GetXJInspectionPlanById(planId);
			if (null != plan)
			{
				model.Id = plan.Id;
				model.PNo = plan.PNo;
				model.Name = plan.Name;
				model.TypeName = Enum.GetName(typeof(InspectionTypeEnum), plan.TypeId);
				model.AimId = plan.AimId;
				model.AimName = Enum.GetName(typeof(AimTypeEnum), plan.AimId);
				model.CategoryNames = string.Join(",", plan.Categorys.Where(m => !m.Deleted && m.Published).Select(x => x.Name).ToArray());
				model.PlaceNames = string.Join(",", plan.Places.Where(m => !m.Deleted && m.Published).Select(x => x.Name).ToArray());
				model.TeamName = _departmentService.GetNameById(plan.TeamId);
				if (plan.PersonId > 0)
					model.PersonName = _customerService.GetNameById(plan.PersonId);
				model.MaintenanceTeamName = _departmentService.GetNameById(plan.MaintenanceTeamId);
				if (plan.MaintenancePersonId > 0)
					model.MaintenancePersonName = _customerService.GetNameById(plan.MaintenancePersonId);
				model.StartOn = plan.StartOn.ToString("yyyy-MM-dd");
				model.EndOn = plan.EndOn.ToString("yyyy-MM-dd");
				model.LastUpdateOn = plan.LastUpdateOn.HasValue ? plan.LastUpdateOn.Value.ToString("yyyy-MM-dd HH:mm") : "";

				#region 当日巡检记录
				DateTime today = DateTime.Today;
				var inspections = _xJInspectionService.GetAllInspections(planId: planId, startOn: today, endOn: today, pageSize: 5);
				if (inspections.Any())
				{
					foreach (var inspection in inspections)
					{
						model.Inspections.Add(new ListItemModel
						{
							Id = inspection.Id,
							Title = inspection.Comment,
							Label = string.Format("{0} {1}", inspection.CustomerName, inspection.CreatedOn.ToString("yyyy-MM-dd")),
							Value = inspection.MaintenanceState > 0 ? Enum.GetName(typeof(MaintenanceStateEnum), inspection.MaintenanceState) : null,
							Url = inspection.MaintenanceId > 0 ? string.Format("/pages/maintenance/detail?id={0}", inspection.MaintenanceId) : null
						});
					}
				}

				#endregion

				// 只要在计划时间内就能继续操作
				if (DateTime.Today >= plan.StartOn && DateTime.Today <= plan.EndOn)
				{
					model.CanDo = true;

					#region 计划巡检点、设备分类
					var categorys = _xJEquipmentCategoryService.GetAllXJEquipmentCategorys().Where(m => !m.IsConsumables);
					var places = _xjPlaceService.GetAllXJPlaces();
					if (planId > 0)
					{
						switch (plan.AimId)
						{
							case (int)AimTypeEnum.设备分类:
								var cs = plan.Categorys.Where(m => !m.Deleted && m.Published);
								if (cs.Any())
								{
									foreach (var c in cs)
									{
										model.AvailableCategories.Add(new SelectItemModel { Id = c.Id, Text = c.Name });
										foreach (var item in categorys.Where(m => m.PId == c.Id))
										{
											model.AvailableCategories.Add(new SelectItemModel { Id = item.Id, Text = item.Name, PId = item.PId });
											foreach (var p in item.Places)
											{
												if (!model.AvailablePlaces.Any(m => m.Id == p.Id))
												{
													model.AvailablePlaces.Add(new SelectItemModel { Id = p.Id, Text = p.Name });
												}
											}
										}
									}
								}
								break;
							case (int)AimTypeEnum.巡检点:
								var ps = plan.Places.Where(m => !m.Deleted && m.Published);
								if (ps.Any())
								{
									foreach (var p in ps)
									{
										model.AvailablePlaces.Add(new SelectItemModel { Id = p.Id, Text = p.Name });
										var ccs = categorys.Where(m => m.Places.Any(c => c.Id == p.Id));
										if (ccs.Any())
										{
											foreach (var c in ccs)
											{
												if (!model.AvailableCategories.Any(m => m.Id == c.Id))
												{
													model.AvailableCategories.Add(new SelectItemModel { Id = c.Id, Text = c.Name, PId = c.PId });
												}
											}
										}
									}
								}
								break;
							default:
								break;
						}
					}
					else
					{
						model.AvailablePlaces = places.Select(x => { return new SelectItemModel { Id = x.Id, Text = x.Name }; }).ToList();
						model.AvailableCategories = categorys.Select(x => { return new SelectItemModel { Id = x.Id, Text = x.Name, PId = x.PId }; }).ToList();
					}
					if (model.AvailablePlaces.Count() == 1)
					{
						var place = model.AvailablePlaces[0];
						if (null != place)
						{
							model.PlaceId = place.Id;
							model.PlaceName = place.Text;
						}
					}
					if (model.AvailableCategories.Count() == 1)
					{
						var category = model.AvailableCategories[0];
						if (null != category)
						{
							model.CategoryId = category.Id;
							model.CategoryName = category.Text;
						}
					}
					#endregion
				}
			}
			return Json(new { resut = true, model });
		}
	}
}